package netty

import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame


class ServerHandler : ChannelInboundHandlerAdapter() {
    //接受client发送的消息
    @Throws(Exception::class)
    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
        println("接收到客户端信息:$msg")
        if (msg is TextWebSocketFrame) {
            when (msg.text()) {
                "echo" -> {
                    ctx?.write(msg)
                }
                "list" -> {
                    ctx?.write(Clients.get().toString())
                    println(Clients.get().toString())
                }
                "count" -> {
                    ctx?.write(Clients.get().size.toString())
                    println(Clients.get().size.toString())
                }
                else -> {
                }
            }
        }

    }

    //通知处理器最后的channelRead()是当前批处理中的最后一条消息时调用
    @Throws(Exception::class)
    override fun channelReadComplete(ctx: ChannelHandlerContext) {
        ctx.flush()
    }

    override fun channelUnregistered(ctx: ChannelHandlerContext?) {
        ctx?.channel()?.id().toString()?.run {
            Clients.remove(this)
        }
        println("连接关闭:${ctx?.channel()?.id()}")
    }

    //读操作时捕获到异常时调用
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        ctx.close()
    }

    //客户端去和服务端连接成功时触发
    @Throws(Exception::class)
    override fun channelActive(ctx: ChannelHandlerContext) {
        ctx.channel().id()?.run {
            Clients.add(this.toString())
            println("连接建立:${this}")
        }
    }

}